package com.psjj.privilege.dao;

import com.psjj.privilege.po.Privilege;
import com.psjj.privilege.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class PrivilegeDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());

    public List<Privilege> queryPrivileges() throws SQLException {
        List<Privilege> list = queryRunner.query("select * from t_privilege", new BeanListHandler<Privilege>(Privilege.class));
        return list;
    }

    public boolean HasPrivilegeIdAndRid(int privilegeId, int rid) throws SQLException {
        Long count = queryRunner.query("select count(*) from t_role_privilege where privilegeid=? and roleid=?",
                new ScalarHandler<Long>(), privilegeId, rid);
        if(count>0){
            return true;
        }
        return false;
    }

    public void clearMidsByRoleId(int rid) throws SQLException{
        queryRunner.update("delete from t_role_privilege where roleid=?",rid);
    }

    public void addPrivilegeIdAndRoleId(int privilegeid, int rid) throws SQLException {
        queryRunner.update("insert into t_role_privilege(privilegeid,roleid) values(?,?)",privilegeid,rid);
    }

    public List<Privilege> queryPrivilegesByRoleId(int roleId)throws SQLException {
        String sql = "select p.* from t_role_privilege rp ,t_privilege p where rp.privilegeid=p.mid and rp.roleid=?";
        List<Privilege> privileges = queryRunner.query(sql, new BeanListHandler<Privilege>(Privilege.class), roleId);
        return privileges;
    }

    public List<String> urls() throws SQLException {
        String sql = "select url from t_privilege where url is not null";
        List<String> urls = queryRunner.query(sql,new ColumnListHandler<String>());
        return urls;
    }
}
